-- UIAwakeCarvingMain
-- Create by chendh
-- 觉醒雕像主界面

-- UIAwakeCarvingMain继承自Layer
UIAwakeCarvingMain = class("UIAwakeCarvingMain", function()
    return cc.Layer:create();
end);

function UIAwakeCarvingMain.create(classId)
    return UIAwakeCarvingMain.new(classId);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIAwakeCarvingMain:ctor(classId)
    -- 初始化
    self:setName("UIAwakeCarvingMain");
    local node = cc.CSLoader:createNode("layout/training/TrainingMain.csb");
    self:addChild(node);
    self.node = node;
    self.classId = classId;

    self.descLabel = findChildByName(self.node, "CT/desc");
    self.desc2Label = findChildByName(self.node, "CT/desc2");
    self.desc3Label = findChildByName(self.node, "CT/desc3");

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIAwakeCarvingMain:redraw()
    local node = self.node;
    local CT   = node:getChildByName("CT");
    local BT   = node:getChildByName("BT");

    -- 显示标题
    local titleLabel = findChildByName(node, "CT/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("awake_carving_title"));

    -- 钻石信息
    local gemNode = findChildByName(BT, "gem");
    gemNode:setVisible(false);

     -- 钻石信息
    local btGemIcon = findChildByName(BT, "gem/icon");
    local btGemNum = findChildByName(BT, "gem/num");
    TextStyleM.setOutlineStyle(btGemNum, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    TextStyleM.setTextStyle(btGemNum, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_WHITE);
    btGemNum:setString(tostring(ME.user:queryAttrib("gem")));
    btGemIcon:setVisible(false);
    btGemNum:setVisible(false);

    local heroId = self.classId;

    if not heroId then
        heroId = AwakeM.getCarvingHeroId();
        self.classId = heroId;
    end

    -- 显示星星
    local heroFrame = findChildByName(CT, "hero_frame");
    heroFrame:loadTextureNormal(getFrameBgIconPath("awake"));
    heroFrame:loadTexturePressed(getFrameBgIconPath("awake"));
    heroFrame:loadTextureDisabled(getFrameBgIconPath("awake"));
    local starNode = findChildByName(heroFrame, "star_node");
    local starShine = heroFrame:getChildByName("star_shine");
    starNode:setVisible(false);
    starShine:setVisible(false);

    -- 获取当前训练室信息
    local icon = findChildByName(CT, "hero_frame/icon");
    local light = findChildByName(CT, "hero_frame/light");
    icon:stopAllActions();
    icon:removeAllChildren();
    light:stopAllActions();
    light:removeAllChildren();

    if heroId == 0 then
        icon:setVisible(false);
        playLearnSkillHintEffect(light, -2, 0);
    else
        -- 加载英雄头像
        --local pet = PetM.getMyPet(heroId);
        --local fileName = pet:getIcon();
        --local iconPath = getHeroIconPath(fileName);
        --icon:loadTexture(iconPath);
        icon:setVisible(true);

        starNode:setVisible(true);
        icon:setOpacity(255);
        playBubbleAnima(icon, false, nil, 0.88, 0.85, 0.8, 0.7);
    end

    -- 显示描述
    TextStyleM.setSubheadStyle(self.descLabel);

    -- 按钮上的文字
    local btnOk = findChildByName(node, "CT/btn_ok");
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_ok"));

    if heroId == 0 then
        btnOk:setBright(false);
        btnOk:setTouchEnabled(false);
    else
        btnOk:setBright(true);
        btnOk:setTouchEnabled(true);
    end

    -- 加速信息默认不显示
    local boostLabel = findChildByName(self.node, "CT/btn_ok/boost_label");
    local gemIcon = findChildByName(self.node, "CT/btn_ok/gem_icon");
    local amountLabel = findChildByName(self.node, "CT/btn_ok/gem_amount");
    boostLabel:setVisible(false);
    gemIcon:setVisible(false);
    amountLabel:setVisible(false);

    -- 隐藏进阶完成光效
    local finishLight = findChildByName(self.node,"CT/finish_light");
    finishLight:setVisible(false);

    self:stopAllActions();

    finishLight:stopAllActions();
    heroFrame:setTouchEnabled(false);

    -- 停止跳动
    setJumpStop("AwakeMain", true);

    -- 宠物模型
    --[[local heroModel = findChildByName(self.node,"CT/hero_frame/model_node");
    heroModel:stopAllActions();
    heroModel:setVisible(false);
    heroModel:removeAllChildren();

    -- 绘制冈布奥模型
    if heroId ~= 0 then
        local pet = PetM.getMyPet(heroId);
        local modelId = pet:getModelId();
        local offsetX = PetM.queryModel(modelId, "offset_x");
        local offsetY = PetM.queryModel(modelId, "offset_y");
        local iconPath = getHeroIconPath(PetM.queryModel(modelId, "icon"));
        local scale = 0.8 * PetM.queryModel(modelId, "model_scale");
        local modelAnim = createHeroModel(modelId, icon, heroModel, scale, iconPath, offsetX, offsetY);

        if modelAnim ~= nil then
            local function playAtkAnim()
                local rand = math.random(1, 2);
                local heroDisplay = findChildByName(heroModel, "HeroDisplay");

                if rand == 1 then
                    -- 播放施法动作
                    heroDisplay:switchAction(HERO_ACTION_CAST_ME);
                else
                    -- 播放攻击动作
                    heroDisplay:switchAction(HERO_ACTION_ATTACK);
                end

                -- 延迟播放攻击动作
                local delayFix = math.random(5, 10);
                performWithDelay(heroModel, playAtkAnim, delayFix);
            end

            heroModel:setVisible(true);

            playAtkAnim();
            --performWithDelay(heroFrame, playAtkAnim, delayFix);
        end
    end]]

    if type(self.desc2Label.initPosition) == "table" then
        local pos = self.desc2Label.initPosition;
        self.desc2Label:setPosition(cc.p(pos.x, pos.y));
    else
        self.desc2Label.initPosition = self.desc2Label:getPosition();
    end

    if type(self.desc3Label.initPosition) == "table" then
        local pos = self.desc3Label.initPosition;
        self.desc3Label:setPosition(cc.p(pos.x, pos.y));
    else
        self.desc3Label.initPosition = self.desc3Label:getPosition();
    end

    -- 获取训练状态
    local state = AwakeM.getCarvingState();

    if state == AwakeM.CARVING_STATE_FINISH then
        self.desc2Label:setVisible(false);
        self.desc3Label:setVisible(true);

        -- 已建造好的，使用已完成的雕像资源
        local iconPath = getAwakeIconPath("carved_big");
        icon:loadTexture(iconPath);
    else
        self.desc2Label:setVisible(true);
        self.desc3Label:setVisible(false);

        -- 未建造好的，使用建造中的雕像资源
        local iconPath = getAwakeIconPath("carving_big");
        icon:loadTexture(iconPath);
    end

    if state == AwakeM.CARVING_STATE_PREPARE then
        TextStyleM.setSubheadStyle(self.desc2Label);
        -- 还未开始
        self.descLabel:setString(getLocStr("awake_carving_subhead"));
        self.desc2Label:setString(getLocStr("awake_carving_desc"));

        heroFrame:setTouchEnabled(true);
    elseif state == AwakeM.CARVING_STATE_FINISH then

        TextStyleM.setTextStyle(self.desc3Label, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        self.desc3Label:setString(getLocStr("awake_carving_finish"));
        convertTextToArtWord(self.desc3Label, "images/ui/text_mask/text_mask3.png", TextStyleM.TEXT_COLOR_DARK_BROWN, TextStyleM.TEXT_OUTLINE_COLOR_DARK);

        -- 进阶已完成
        self.descLabel:setString(string.format(getLocStr("awake_is_carving"), PetM.query(heroId, "short_name")));

        -- 进阶完成光效可见
        finishLight:setVisible(true);

        -- 光效旋转效果
        local action = cc.RotateBy:create(5, 360);
        finishLight:runAction(cc.RepeatForever:create(action));

        -- 字体跳动
        local nameCount = string.getWCharCount(self.desc3Label:getString());
        setArtWordJump(nameCount, self.desc3Label, self.node, "AwakeMain", 0.2);

    elseif state == AwakeM.CARVING_STATE_UPGRADING then
        -- 进阶中
        self.descLabel:setString(string.format(getLocStr("awake_is_carving"), PetM.query(heroId, "short_name")));

        btGemIcon:setVisible(true);
        btGemNum:setVisible(true);

        TextStyleM.setSubheadStyle(self.desc2Label);

        -- 开始定时更新
        self:startTick();
    end
end

-- 开始定时更新
function UIAwakeCarvingMain:startTick()
    local btnOk = findChildByName(self.node, "CT/btn_ok");

    local function tick()
        if AwakeM.getCarvingState() ~= AwakeM.CARVING_STATE_UPGRADING then
            self:redraw();
        else
            -- 当前剩余时间
            local finishTime = AwakeM.getCarvingFinishTime();
            local serverTime = TimeM.getServerTime();
            local leftTime = finishTime - serverTime;
            if leftTime < 0 then
                leftTime = 0;
            end

            local hours = math.floor(leftTime / 3600);
            local mins =  math.floor((leftTime % 3600) / 60);
            local secs =  math.floor((leftTime % 3600) % 60);

            local desc = string.format(getLocStr("slime_upgrading"), hours, mins, secs);

            -- 进阶中
            --TextStyleM.setSubheadStyle(self.desc2Label);
            self.desc2Label:setString(desc);

            -- 显示加速完成
            btnOk:setTitleText("");
            self:showBoostText(leftTime);

            if leftTime > 0 then
                performWithDelay(self, tick, 1);
            else
               self:redraw();
            end
        end
    end

    tick();
end

-- 显示加速完成文字
function UIAwakeCarvingMain:showBoostText(leftTime)
    -- 显示加速
    local boostLabel = findChildByName(self.node, "CT/btn_ok/boost_label");
    TextStyleM.setTextStyle(boostLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, nil, nil, nil, nil, nil, true);
    boostLabel:setString(getLocStr("slime_upgrade_boost"));
    boostLabel:setVisible(true);

    -- 消耗价格
    local heroId = self.classId;
    local pet = PetM.getMyPet(heroId);
    local cost = FormulaM.invoke("CALC_PET_CARVING_BOOST_COST", pet, leftTime);
    local amount = cost[3];
    self.gemAmout = amount;
    local amountLabel = findChildByName(self.node, "CT/btn_ok/gem_amount");
    TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, nil, nil, nil, nil, nil, true);
    amountLabel:setString(tostring(amount));
    amountLabel:setVisible(true);

    -- 钻石不足时，显示红色
    local curGem = ME.user:queryAttrib("gem");
    if curGem < self.gemAmout then
        amountLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
    else
        amountLabel:setTextColor(TextStyleM.TEXT_COLOR_BROWN_YELLOW);
    end

    -- 钻石图标对齐
    local gemIcon = findChildByName(self.node, "CT/btn_ok/gem_icon");
    gemIcon:setPositionX(amountLabel:getPositionX() - amountLabel:getContentSize().width - 30);
    gemIcon:setVisible(true);
end

-- 注册事件处理回调函数
function UIAwakeCarvingMain:registerEventCallback()
    -- 注册事件
    EventMgr.register("UIAwakeCarvingMain", event.USER_INFO_UPDATED, function(args)
        if args == "carving_room" then
            self.classId = AwakeM.getCarvingHeroId();
            self:redraw();
        end
    end);

    -- 注册开始雕刻雕像的回调
    EventMgr.register("UIAwakeCarvingMain", event.AWAKE_CARVING_FINISH, function(args)
        self:whenCarvingFinish(args);
    end)

    -- 注册获得焦点的回调
    EventMgr.register("UIAwakeCarvingMain", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIAwakeCarvingMain" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            -- 显示界面
            self:setVisible(true);

        elseif para["lose"] == "UIAwakeCarvingMain" then
            -- 隐藏界面
            self:setVisible(false);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIAwakeCarvingMain");
        elseif eventType == "enter" then

        end
    end);
end

-- 注册点击事件
function UIAwakeCarvingMain:registerTouchEvent()
    local node = self.node;

    local hero_frame = findChildByName(node, "CT/hero_frame");
    hero_frame:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if AwakeM.getCarvingFinishTime() ~= -1 then
                -- 已经在升阶或者升阶已完成，无法再选择
                -- 显示升阶详细信息
                local uiItemDesc = UITrainingItemDesc.create(AwakeM.getCarvingHeroId());
                UIMgr:getCurrentScene():addForm(uiItemDesc);
                AudioM.playFx("button_spell");
                return;
            end

            -- 打开英雄选择界面
            require "game/ui/form/awake/UIAwakeCarvingSelect"
            local uiForm = UIAwakeCarvingSelect.create();
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("ui_open1");
        end
    end);

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIAwakeCarvingMain");
            AudioM.playFx("button_return");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确认按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    btnOk:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local heroId = self.classId;
            if heroId == 0 then
                alert(getLocStr("please_select_a_pet"));
                return;
            end

            local state = AwakeM.getCarvingState();

            if state == AwakeM.CARVING_STATE_PREPARE then
                local ret = AwakeM.canCarving(heroId);
                if ret ~= true then
                    return alert(getLocStr(ret));
                end

                -- 已选定，打开雕刻确认界面
                require "game/ui/form/awake/UIAwakeCarvingConfirm"
                local uiForm = UIAwakeCarvingConfirm.create(heroId);
                UIMgr.getCurrentScene():addForm(uiForm);
            elseif state == AwakeM.CARVING_STATE_FINISH then
                -- 结束雕刻
                Operation.cmd_awake_carving_finish(heroId);
            else
                local curGem = ME.user:queryAttrib("gem");
                if curGem < self.gemAmout then
                    -- 钻石不足提示
                    showGemLackConfirm();
                    return;
                end

                -- 加速雕刻
                local okFunc = function()
                    AwakeM.boostCarving(heroId);
                end

                local tipTxt = string.format(getLocStr("awake_carving_boost_comfirm"), self.gemAmout or 0);
                confirm2(CONFIRM_TYPE_OK, getLocStr("slime_upgrade_boost"), tipTxt, okFunc);
            end
        end
    end);

    -- 注册图鉴按钮点击事件
    local btnHandBook = findChildByName(node, "BT/btn_handbook");
    local function onHandBookClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 打开雕像图鉴界面
            require "game/ui/form/awake/UIAwakeCarvingList"
            local uiForm = UIAwakeCarvingList.create();
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("button_return");
        end
    end
    btnHandBook:setVisible(true);
    btnHandBook:addTouchEventListener(onHandBookClick);
    TextStyleM.setTextStyle(btnHandBook, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnHandBook:setTitleText(getLocStr("btn_text_handbook"));
end

-- 雕像建造结束的回调
function UIAwakeCarvingMain:whenCarvingFinish(args)
    local classId = args["class_id"];
    local prop = args["prop"][1];

    local pet = PetM.getMyPet(classId);
    -- 显示升级光效
    local starNum = pet:getRank();
    AudioM.playFx("new_level");

    local parameters = {};
    parameters.classId = classId;
    parameters.starNum = starNum;
    parameters.specialProp = prop;

    local arr = {{"talent_skill_level", 1},}
    local carvingProp = AwakeM.query(classId, "prop");

    for _, info in ipairs(carvingProp) do
        table.insert(arr, {info[2], info[3]});
    end
    table.insert(arr, {prop[2], prop[3]});
    parameters.arr = arr;

    if UIMgr.getCurrentScene():isOpen("UIHeroUpgradeRankEffect") then
        UIMgr.getCurrentScene():removeFormByName("UIHeroUpgradeRankEffect");
    end
    require "game/ui/form/hero/UIHeroUpgradeRankEffect"
    local uiHeroUpgradeRankEffect = UIHeroUpgradeRankEffect.create(parameters, "carving");
    UIMgr.getCurrentScene():addForm(uiHeroUpgradeRankEffect);

    -- 关闭当前界面
    UIMgr.getCurrentScene():removeFormByName("UIAwakeCarvingMain");
end

-- 描述文本飞入
function UIAwakeCarvingMain:descLabelFlyIn(label)
    local duration = 0.2;
    local offsetX = DESIGN_WIDTH;
    local oldPosX = 0;
    local oldPosY = label:getPositionY();
    label:setPosition(cc.p(oldPosX - offsetX, oldPosY)); -- 从左边飞入

    local function play()
        local moveUp = cc.EaseIn:create(cc.MoveTo:create(duration, cc.p(oldPosX, oldPosY + 5)), 0.3);
        local moveDown = cc.EaseIn:create(cc.MoveTo:create(0.1, cc.p(oldPosX, oldPosY - 3)), 0.3);
        local moveUp2 = cc.EaseIn:create(cc.MoveTo:create(0.1, cc.p(oldPosX, oldPosY)), 0.3);
        local action = cc.Sequence:create(moveUp ,moveDown, moveUp2);
        label:runAction(action);
    end

    label:stopAllActions();
    performWithDelay(label, play, 0.2);
end

